﻿using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using AvalonDock;
using Foundation;
using Foundation.ExtensionMethods;
using Foundation.MarkupExtensions;
using Poet.Modules;
using Poet.ViewModels;
using DataFormats = System.Windows.DataFormats;
using DragEventArgs = System.Windows.DragEventArgs;
using ToolBar = System.Windows.Controls.ToolBar;

namespace Poet.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class TrunkView
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="TrunkView"/> class.
        /// </summary>
        public TrunkView()
        {    
            InitializeComponent();
            var toolBars = (XamlCollection)Resources["MainToolBarCollection"];

            foreach (ToolBar toolBar in toolBars)
            {
                ToolBarTray.ToolBars.Add(toolBar);
            }

            ThemeManager.SetDefaultAvalonDockTheme();
            //HwndSource.DefaultAcquireHwndFocusInMenuMode = false;
            Keyboard.DefaultRestoreFocusMode = RestoreFocusMode.None;

            var lastFocusedElement = Keyboard.FocusedElement;
            InputManager.Current.EnterMenuMode += delegate { lastFocusedElement = Keyboard.FocusedElement; };
            InputManager.Current.LeaveMenuMode += delegate
                {
                    if (lastFocusedElement != null)
                        lastFocusedElement.Focus();
                };
          
            Closing +=
                (o, e) =>
                    {
                        TrunkViewModel.IsShown = false;
                        e.Cancel = true;
                    };

            ViewModel.ApplicationClosing += () => ViewModeManager.SaveCurrent(DockingManager);
            DockingManager.Loaded += (sender, args) => ViewModeManager.LoadCurrent(DockingManager);
            if(Pane.Items.Count > 0) ((ManagedContent)Pane.Items[0]).Activate();
        }

        private TrunkViewModel TrunkViewModel
        {
            get { return DataContext as TrunkViewModel; }
        }

        private void DockingManagerMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var documentPanes = DockingManager.GetVisualDescendants<DocumentPane>();

            foreach (var pane in documentPanes)
            {
                pane.MouseDoubleClick -= DocumentPaneMouseDoubleClick;
                pane.MouseDoubleClick += DocumentPaneMouseDoubleClick;
            }

            if (DockingManager.Documents.Count == 0 && e.OriginalSource is Border)
                CreateNewOrOpenDocument(e);
        }

        private void DocumentPaneMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (!(e.OriginalSource is Border)) return;
            DockingManager.MainDocumentPane = (DocumentPane)sender;
            CreateNewOrOpenDocument(e);
        }

        private void CreateNewOrOpenDocument(MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
                ApplicationCommands.New.Execute(null, this);

            if (e.ChangedButton == MouseButton.Right)
                ApplicationCommands.Open.Execute(null, this);
        }

        private void ChangeWindowState(object sender, MouseButtonEventArgs e)
        {
            return;
            if (e.ChangedButton == MouseButton.Left)
                WindowState = WindowState == WindowState.Normal ? WindowState.Maximized : WindowState.Normal;
            if (e.ChangedButton == MouseButton.Right)
                WindowState = WindowState == WindowState.Normal ? WindowState.Minimized : WindowState.Normal;
        }

        private void DockingManagerDrop(object sender, DragEventArgs e)
        {
            var fileNames = e.Data.GetData(DataFormats.FileDrop) as string[];
            if (fileNames != null)
                ApplicationCommands.Open.Execute(fileNames.ToArray(), this);

            var text =
                Keyboard.Modifiers == ModifierKeys.Control
                    ? e.Data.GetData(DataFormats.Html) as string
                    : e.Data.GetData(DataFormats.Text) as string;

            if (text != null)
                ApplicationCommands.New.Execute(text, this);
        }
    }
}
